package PersonStu.sanqi;

import java.util.TreeMap;

/**
 * @Author: Dijah
 * @Date: 2022/10/28 17:26
 * @Desc:
 * 给定一个字符串数组arr
 * String[] arr = {"b\st","d\","a\d\e","a\b\c"};
 * 把这些路径中的目录结构打印出来，子目录直接列在父目录下面，如下
 * a
 *  b
 *    c
 *  d
 *   e
 * b
 *  cst
 * d
 */
public class code_08_getFolderTree {

    //构造一个Node
    public static class Node{
        //上一个节点是通过哪条路到我的
        public String path;

        //key:node下级的路  value:node在key这条路上对应的节点是什么
        // 为什么使用treeMap？因为看字母是按照顺序来排列的
        public TreeMap<String,Node> nextMap;
        public Node(String p){
            this.path = p;
            nextMap = new TreeMap<>();
        }
    }

    //打印树型
    public static void print(String [] folders){
        if(folders.length == 0 || folders == null){
            return;
        }
        //根据所有的字符串，把前缀树建立好，头节点为head
        Node head = generateFolderTree(folders);
        //打印
        printProcess(head,0);
    }

    /**
     * 建立前缀树
     * @param folders
     * @return
     */
    private static Node generateFolderTree(String[] folders) {
        Node head = new Node("");
        for (String folder : folders) {
            //用来做分割的
            String [] paths = folder.split("\\\\");
            Node cur = head;
            for (int i = 0; i < paths.length; i++) { // a,b,c
                if(!cur.nextMap.containsKey(paths[i])){
                    cur.nextMap.put(paths[i],new Node(paths[i]));
                }
                //如果已经存在nextMap中了,那么直接从nextMap中获取当前位置的节点
                cur = cur.nextMap.get(paths[i]);
            }
        }
        return head;
    }


    /**
     * 打印
     * @param node head节点
     * @param level 当前在level层
     */
    private static void printProcess(Node node, int level) {
        if(level != 0){
            System.out.println(get4nSpace(level) + node.path);
        }
        for (Node next : node.nextMap.values()) {
            printProcess(next,level + 1);
        }
    }

    private static String get4nSpace(int level) {
        //拼接空格
        String res = "";
        for (int i = 1; i < level; i++) {
            res += "    ";
        }
        return res;
    }

    public static void main(String[] args) {
        String[] fo = {"a\\b\\c","a\\b\\s" , "a\\d\\e" ,"e\\f\\sty"  };
        print(fo);
    }

}
